package main

import (
  "tnet"
  "io"
  "os"
  )

func main() {

  // Test PairArray and Pair
  c1 := tnet.Chunk{[]byte("foo"), byte(',')}
  c2 := tnet.Chunk{[]byte("bar"), byte(',')}

  p := tnet.Pair{c1, c2}
  tnet.Log("pair: %q", p)

  tnet_map := tnet.PairArray{}
  tnet_map = append(tnet_map, p)

  c3 := tnet.Chunk{[]byte("xxx"), byte(',')}
  c4 := tnet.Chunk{[]byte("yyy"), byte(',')}
  tnet_map = append(tnet_map, tnet.Pair{c3, c4})

  tnet.Log("map: ", tnet_map)

  value, ok := tnet_map.Get("foo")
  tnet.Log("value: %s", value)
  tnet.Log("ok: ", ok)

  // Nonexistent
  value, ok = tnet_map.Get("")
  tnet.Log("value: ", value)
  tnet.Log("ok: ", ok)

  tnet.Log("hello, world")

  // Read from stdin

  // TODO: Read length prefix in Go
  stdin := io.Reader(os.Stdin);

  if len(os.Args) < 2 {
    tnet.Log("No action")
    os.Exit(1)
  }

  action := os.Args[1]

  if action == "read-dict" {

    chunk, _ := tnet.Read(stdin)
    tnet.Log("payload: %q", chunk.Payload)
    tnet.Log("tag: %q", chunk.Tag)

    dict, _ := tnet.ParseDictChunks(chunk.Payload);
    tnet.Log("deserialized dict: %s", dict)

    m := make(map[string] string)
    m["foo"] = "bar"
    m["spam"] = "eggs"
    out := tnet.DumpDict(m)
    tnet.Log("Serialized dict: %s", out)

    // TODO: check EOF and such

    /*
    buf, tag = tnet.Read(stdin)
    dict, _ = ParseDictChunksPrefix(buf);
    tnet.Log("deserialized dict: %s", dict);
    */
  } else if action == "nested" {

    chunk, _ := tnet.Read(stdin)
    if chunk.Tag != byte('}') {
      os.Exit(1)
    }
    dict, _ := tnet.ParseDictChunks(chunk.Payload);
    tnet.Log("deserialized dict: %s", dict)

    subchunk, _ := dict.Get("dict");
    tnet.Log("subchunk %q", subchunk)

    if subchunk.Tag != byte('}') {
      tnet.Log("Expected }")
    }

    subdict, _ := tnet.ParseDictChunks(subchunk.Payload);
    tnet.Log("deserialized subdict: %s", subdict)

  } else if action == "read" {
    // Implement interfaces?
    // tnet.Reader
    // tnet.Writer
    // tnetb.Reader

    chunk, _ := tnet.Read(stdin)
    tnet.Log("buf: %q", chunk.Payload)
    tnet.Log("tag: %q", chunk.Tag)

  } else if action == "dump" {
    tnet.Log("DUMPING")
    //buf := make([]byte, 0)
    buf := tnet.DumpString("foo")
    tnet.Log("buf: %q", buf)

  } else if action == "stdin" {

    // do we really need to make a slice to read 1 byte?
    b := make([]byte, 1)
    stdin.Read(b)
    tnet.Log("read  byte: %q", b)

  } else {
    tnet.Log("Invalid action: %s", action);
  }
}


